package com.tticar.invmanager.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

/**
 * Created by yandou on 17/12/4.
 */
@Component
public class MyBeanUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    // load
    private static DefaultListableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (MyBeanUtils.applicationContext == null) {
            MyBeanUtils.applicationContext = applicationContext;
        }
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
        beanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static void registerBean(String beanName, Object singletonObject) {
        beanFactory.registerSingleton(beanName, singletonObject);
    }

    public static void destroyBean(String beanName) {
        beanFactory.destroyBean(beanName);
    }
}
